package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.item.clients.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderFormDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.entity.enums.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import dto.AddressDTO;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.soap.Detail;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailService detailService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderLogisticsService logisticsService;

    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderDTO) {
        Order order = new Order();
        Long id = UserContext.getUser().getId();
        order.setUserId(id);
        //金额相关信息
        Map<Long, Integer> carts = orderDTO.getCarts();

        //获取所有sku的id
        List<Long> idList = new ArrayList<>(carts.keySet());
        //查询sku
        List<SkuDTO> skuList = itemClient.querySkuBySpuId(idList);
        //计算金额总和
        long total = 0;
        for (SkuDTO sku : skuList) {
            //获取数量
            int num = carts.get(sku.getId());
            // 计算总金额
            total += sku.getPrice() * num;
        }
        //填写金额数据
        order.setTotalFee(total);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setPostFee(0L);
        order.setActualFee(total + order.getPostFee()/* - 优惠金额*/);
        order.setStatus(OrderStatus.INIT);
        // 写order到数据库
        boolean success = save(order);

        //2,写orderdetail

        //定义一个集合
        List<OrderDetail> details = new ArrayList<>();

        for (SkuDTO sku : skuList) {
            //商品数量
            int num = carts.get(sku.getId());
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(order.getOrderId());
            detail.setImage(StringUtils.substringBefore(sku.getImages(), ","));
            detail.setNum(num);
            detail.setSkuId(sku.getId());
            detail.setSpec(sku.getSpecialSpec());
            detail.setPrice(sku.getPrice());
            detail.setTitle(sku.getTitle());
            details.add(detail);
        }
        // 2.3.批量新增
        success = detailService.saveBatch(details);

        if (!success) {
            throw new LyException(500, "订单创建失败！");
        }
        //3.写orderLogistics
        // 3.1.查询收货地址
        AddressDTO address = userClient.queryAddressById(orderDTO.getAddressId());
        //填写物流信息
        //转化成entity
        OrderLogistics logistics = address.toEntity(OrderLogistics.class);
        logistics.setOrderId(order.getOrderId());

        // 3.3.写入数据库
        success = logisticsService.save(logistics);
        if(!success){
            throw new LyException(500, "订单创建失败！");
        }

        // 4.减库存
        try {
            itemClient.deductStock(carts);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());
        }
        // 返回订单编号
        return order.getOrderId();
    }
}